package com.outsourcing.bottle.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ext.SatelliteMenu;
import android.view.ext.SatelliteMenu.SateliteClickedListener;
import android.view.ext.SatelliteMenuItem;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.domain.LoginUserInfoEntry;
import com.outsourcing.bottle.domain.MyFriendEntry;
import com.outsourcing.bottle.domain.MyFriendInfo;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ImageLoader;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.widget.CustomListView;

/**
 * 
 * @author 06peng
 * 
 */
public class FriendListActivity extends BasicActivity implements
		OnClickListener, Callback, OnScrollListener {

	private static final int INIT_FRIEND_FEED = 0;
	private static final int GET_MORE_DATA = 1;
	private static final int ERROR = 2;
	private static final String TAG = FriendListActivity.class.getSimpleName();
	private static final int EXEU_GET_FRIEND_NOTHING = 3;

	private final int user_baseinfo_notfull = 4;
	private final int complete_info = 5;

	private ImageView backView;
	private ImageView addView;
	private TextView titleView;
	private ImageView spaceView;
	private CustomListView refreshView;

	private final int menu_uploadphoto = 15;
	private final int menu_exprofile = 14;
	private final int menu_exphoto = 13;
	private final int menu_gainbt = 12;
	private final int menu_sendbt = 11;

	private Handler handler;
	private int page = 1;

	private int visibleLastIndex = 0; // 最后的可视项索引
	private View loadMoreView;

	private int ouid;
	private MyFriendInfo myfriendInfo;
	private List<MyFriendEntry> myFriendEntries;
	private FriendListAdapter myFriendAdapter;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.friend_feeds_layout);
		handler = new Handler(this);
		ouid = getIntent().getIntExtra("ouid", 0);
//		imageLoader = new ImageLoader(this, AppContext.UserAvatarIcon);
//		imageLoader2 = new ImageLoader(this, AppContext.BottleTimelineIcon);
		initWidget();
		initSateMenu();
		UICore.eventTask(this, this, INIT_FRIEND_FEED, "", null);
	}

	private void initWidget() {
		backView = (ImageView) findViewById(R.id.topbar_back);
		backView.setOnClickListener(this);
		addView = (ImageView) findViewById(R.id.topbar_menu);
		addView.setOnClickListener(this);
		titleView = (TextView) findViewById(R.id.topbar_title);
		titleView.setVisibility(View.VISIBLE);
		spaceView = (ImageView) findViewById(R.id.topbar_space);
		spaceView.setOnClickListener(this); 
		refreshView = (CustomListView) findViewById(R.id.list_view);
		refreshView.setonRefreshListener(new CustomListView.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				page = 1;
				UICore.eventTask(FriendListActivity.this, FriendListActivity.this, INIT_FRIEND_FEED, null, null);
			}
		});
		loadMoreView = LayoutInflater.from(this).inflate(R.layout.refreshable_list_footer, null);
		loadMoreView.setVisibility(View.GONE);
		refreshView.addFooterView(loadMoreView);
		refreshView.setOnScrollListener(this);
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case INIT_FRIEND_FEED:

			myFriendAdapter = new FriendListAdapter(FriendListActivity.this,
					myFriendEntries);
			refreshView.setAdapter(myFriendAdapter);
			break;
		case ERROR:
			onToast((String) msg.obj);
			break;
		case GET_MORE_DATA:
			myFriendAdapter.notifyDataSetChanged();
			// refreshView.onRefreshComplete();
			break;
		case user_baseinfo_notfull:
			showChoseMes(getString(R.string.exchange_complete_profile_tips),
					complete_info);
			break;
		case EXEU_GET_FRIEND_NOTHING:
			loadMoreView.setVisibility(View.GONE);
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		if (v == backView) {
			finish();
		} else if (v == addView) {
			Intent intent = new Intent(this, MoreActivity.class);
			startActivity(intent);
		} else if (v == spaceView) {
			Intent intent = new Intent(this, UserSpaceActivity.class);
			intent.putExtra("ouid", AppContext.getInstance().getLogin_uid());
			startActivity(intent);
		}
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case INIT_FRIEND_FEED:
			getFriendsList(page, -1, ouid);
			break;
		case GET_MORE_DATA:
			getMoreFriendsList(page, -1, ouid);
			break;
		default:
			break;
		}
	}

	/***
	 * 获取好友列表
	 * 
	 * @param page
	 */
	private void getFriendsList(int page, int groupid, int ouid) {
		StringBuffer url = new StringBuffer(UrlConfig.get_friends_list);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&groupid=" + groupid);
		url.append("&ouid=" + ouid);
		url.append("&count=20");
		url.append("&page=" + page);
		ServiceUtils.dout("getFriendsList url: " + url.toString());

		try {
			String results = HttpUtils.doGet(url.toString());

			if (results == null) {
				return;
			}
			ServiceUtils.dout("getFriendsList results:" + results.toString());
			Gson gson = new Gson();
			myfriendInfo = gson.fromJson(results, MyFriendInfo.class);
			if (myfriendInfo.getResults().getAuthok() == 1) {

				myFriendEntries = myfriendInfo.getFriends_list();
				Message message = handler.obtainMessage(INIT_FRIEND_FEED);
				handler.sendMessage(message);
			} else {
				Message message = handler.obtainMessage(ERROR, myfriendInfo
						.getResults().getErrmsg());
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/***
	 * 获取更多好友列表
	 * 
	 * @param page
	 */
	private void getMoreFriendsList(int page, int groupid, int ouid) {
		StringBuffer url = new StringBuffer(UrlConfig.get_friends_list);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&groupid=" + groupid);
		url.append("&ouid=" + ouid);
		url.append("&count=20");
		url.append("&page=" + page);
		ServiceUtils.dout("getMoreFriendsList url: " + url.toString());

		try {
			String results = HttpUtils.doGet(url.toString());

			if (results == null) {
				return;
			}
			ServiceUtils.dout("getMoreFriendsList results:"
					+ results.toString());
			Gson gson = new Gson();
			myfriendInfo = gson.fromJson(results, MyFriendInfo.class);
			if (myfriendInfo.getResults().getAuthok() == 1) {
				List<MyFriendEntry> moreEntries = myfriendInfo
						.getFriends_list();
				if (null != moreEntries && moreEntries.size() > 0) {
					myFriendEntries.addAll(moreEntries);
					Message message = handler.obtainMessage(GET_MORE_DATA);
					handler.sendMessage(message);
				} else {
					Message message = handler
							.obtainMessage(EXEU_GET_FRIEND_NOTHING);
					handler.sendMessage(message);
				}

			} else {
				Message message = handler.obtainMessage(ERROR, myfriendInfo
						.getResults().getErrmsg());
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initSateMenu() {
		SatelliteMenu menu = (SatelliteMenu) findViewById(R.id.menu);
		menu.setVisibility(View.VISIBLE);
		List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>();
		items.add(new SatelliteMenuItem(menu_exprofile, R.drawable.menu_exprofile));
		items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto));
		items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt));
		items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt));
		items.add(new SatelliteMenuItem(menu_uploadphoto, R.drawable.menu_uploadphoto));
		menu.addItems(items);
		menu.setOnItemClickedListener(new SateliteClickedListener() {

			public void eventOccured(int id) {
				switch (id) {
				case menu_sendbt: // 扔瓶子
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent throwIntent = new Intent(
										FriendListActivity.this,
										ChooseBottleActivity.class);
								throwIntent.putExtra("type", "throw");
								startActivity(throwIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_gainbt: // 捞瓶子
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent tryIntent = new Intent(
										FriendListActivity.this,
										ChooseBottleActivity.class);
								tryIntent.putExtra("type", "try");
								startActivity(tryIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_exphoto: // 交换照片
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent exchangeInfoIntent = new Intent(
										FriendListActivity.this,
										ChooseFriendActivity.class);
								exchangeInfoIntent
										.putExtra(
												"choose_friend_type",
												AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE);
								startActivity(exchangeInfoIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_exprofile: // 交换资料
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								LoginUserInfoTable userTable = new LoginUserInfoTable();
								LoginUserInfoEntry userEntry = userTable
										.getLoginUserInfo(AppContext
												.getInstance().getLogin_uid());
								if (userEntry.getBasicinfo_fullfill() == 0) {
									handler.sendEmptyMessage(user_baseinfo_notfull);
								} else {
									Intent exchangeFileIntent = new Intent(
											FriendListActivity.this,
											ChooseFriendActivity.class);
									exchangeFileIntent
											.putExtra(
													"choose_friend_type",
													AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE);
									startActivity(exchangeFileIntent);
								}
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_uploadphoto:
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent intent = new Intent(FriendListActivity.this, ExpandEditActivity.class);
								Bundle extras = new Bundle();
								extras.putString("from_type", AppContext.UPLOAD_PHOTO);
								extras.putInt("albumid", 0);
								extras.putInt("ouid", AppContext.getInstance().getLogin_uid());
								intent.putExtras(extras);
								startActivity(intent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				default:
					break;
				}
			}
		});
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
//		this.visibleItemCount = visibleItemCount;
		visibleLastIndex = firstVisibleItem + visibleItemCount;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		int itemsLastIndex = myFriendAdapter.getCount() + 1; // 数据集最后一项的索引
		int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项 和 head项
		ServiceUtils.dout(TAG + " visibleLastIndex:" + visibleLastIndex);
		ServiceUtils.dout(TAG + "        lastIndex:" + lastIndex);
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
				&& visibleLastIndex == lastIndex) {
			// 如果是自动加载,可以在这里放置异步加载数据的代码
			loadMoreView.setVisibility(View.VISIBLE);
			page++;
			UICore.eventTask(FriendListActivity.this, FriendListActivity.this,
					GET_MORE_DATA, null, null);
		}
	}

	public class FriendListAdapter extends BaseAdapter {

		private Context context = null;
		private List<MyFriendEntry> mbtfriendList = null;
		private ImageLoader imageLoader = null;

		public FriendListAdapter(Context context,
				List<MyFriendEntry> mbtfriendList) {
			this.context = context;
			this.mbtfriendList = mbtfriendList;
			imageLoader = new ImageLoader(context, AppContext.BottleTimelineIcon);
		}

		@Override
		public int getCount() {
			return mbtfriendList.size();
		}

		@Override
		public Object getItem(int position) {
			return mbtfriendList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			BTFriendViewHolder holder = null;
			if (convertView == null
					|| ((BTFriendViewHolder) convertView.getTag()).flag != position) {
				holder = new BTFriendViewHolder();
				System.out.println("position===== convertView=null ===="
						+ position);
				convertView = LayoutInflater.from(context).inflate(
						R.layout.bottle_list_avatar_item, null);
				holder.flag = position;
				holder.mAuthorView = (ImageView) convertView
						.findViewById(R.id.iv_author_photo);
				holder.mExType = (ImageView) convertView
						.findViewById(R.id.iv_bottle_type);
				holder.mExType.setVisibility(View.GONE);
				// content layout
				LinearLayout contentLayout = (LinearLayout) convertView
						.findViewById(R.id.feed_post_body);
				View view = LayoutInflater.from(context).inflate(
						R.layout.mygroupfriend_list_item, null);
				holder.mNickName = (TextView) view
						.findViewById(R.id.tv_onickname);
				holder.mSex = (ImageView)view.findViewById(R.id.bt_sex);
				holder.mDoing = (TextView) view.findViewById(R.id.tv_odoing);
				holder.mLocation = (TextView) view
						.findViewById(R.id.tv_olocation);

				contentLayout.addView(view);

				final MyFriendEntry myFriendEntry = (MyFriendEntry) getItem(position);

				try {
					imageLoader.DisplayImage(myFriendEntry.getFavatar(),
							holder.mAuthorView, R.drawable.avatar_default_big);
				} catch (Exception e) {
					e.printStackTrace();
					holder.mAuthorView
							.setImageResource(R.drawable.avatar_default_big);
				}
				holder.mAuthorView
						.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								Intent spaceIntent = new Intent(context, UserSpaceActivity.class);
								spaceIntent.putExtra("ouid", myFriendEntry.getFuid());
								context.startActivity(spaceIntent);
							}
						});

				String nickName = "<font color='#0099FF'>"
						+ myFriendEntry.getFnickname() + "</font>";
//				String sex = (((myFriendEntry.getFsex()) == 1) ? ("("
//						+ TextUtil.R("login_txt_register_male") + ")") : ("("
//						+ TextUtil.R("login_txt_register_female") + ")"));
				holder.mNickName.setText(Html.fromHtml(nickName));
				int sex_res = myFriendEntry.getFsex() == 1 ? R.drawable.male:R.drawable.female;
				holder.mSex.setBackgroundResource(sex_res);
				if (null != myFriendEntry.getFdoing()
						&& myFriendEntry.getFdoing().length() > 0) {
					holder.mDoing.setVisibility(View.VISIBLE);
					String doingTips = "<font color='#000000'>"
							+ TextUtil.R("friend_doing_tips") + "</font>";
					holder.mDoing.setText(Html.fromHtml(doingTips
							+ myFriendEntry.getFdoing()));
				} else {
					holder.mDoing.setVisibility(View.GONE);
				}
				if ((null != myFriendEntry.getFcountry() && myFriendEntry
						.getFcountry().length() > 0)
						|| (null != myFriendEntry.getFcity() && myFriendEntry
								.getFcity().length() > 0)) {
					holder.mLocation.setVisibility(View.VISIBLE);
					String fromTips = "<font color='#000000'>"
							+ TextUtil.R("friend_comfrom_tips") + "</font>";
					holder.mLocation.setText(Html.fromHtml(fromTips
							+ myFriendEntry.getFcity() + " "
							+ myFriendEntry.getFcity()));

				} else {
					holder.mLocation.setVisibility(View.GONE);
				}

				convertView.setTag(holder);
			} else {
				holder = (BTFriendViewHolder) convertView.getTag();
			}

			return convertView;
		}

		class BTFriendViewHolder {
			public ImageView mSex;
			ImageView mAuthorView;
			ImageView mExType;
			TextView mNickName;
			TextView mDoing;
			TextView mLocation;

			int flag;
		}

	}

}
